package com.jmlee.controller;

import com.jmlee.avo.ChooseSelectVo;
import com.jmlee.component.HostHolder;
import com.jmlee.pojo.Acarousel;
import com.jmlee.pojo.Admin;
import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.PageBean;
import com.jmlee.service.CarouselService;
import com.jmlee.util.JSONUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 广告管理
 *
 * @author xl W
 * @date 2021/3/13 15:56
 */

@Controller
class CarouselController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private CarouselService carouselService;

    @Value("${default.path.upload}")
    private String uploadPath;

    @Value("${default.path.domain}")
    private String domain;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    //====================================广告管理======================================================

    /**
     * 广告管理列表
     *
     * @author xl W
     * @date 2021/3/9 20:19
     */

    //跳转前台用户页面
    @RequestMapping("turnCarousel")
    public String turnCarousel() {
        Admin admin = hostHolder.getAdmin();
        if (admin.getRoleId() == 1L || admin.getRoleId() == 3L) {
//            System.out.println("店要转了");

            return "carousel";

        } else {
//            System.out.println("分店要转了");
            return "aCarousel";
        }

    }

    //分店查看广告列表
    @RequestMapping("aCarouselCount")
    @ResponseBody
    public String sCount(Acarousel acarousel, HttpServletRequest request, HttpServletResponse response) throws IOException {
//        System.out.println("分店进来了");
        Admin admin = hostHolder.getAdmin();


        int curPage = Integer.valueOf(request.getParameter("page"));
        int pageSize = Integer.valueOf(request.getParameter("limit"));

//        System.out.println(acarousel.toString());

        RowBounds rowBounds = new RowBounds((curPage - 1) * pageSize, pageSize);
        PageBean<Acarousel> pageBean = new PageBean<>();

        pageBean.setCode(0);
        int count = carouselService.selectSAdAcListCount(acarousel,admin.getId());

        pageBean.setCount(count);
        pageBean.setData(carouselService.selectSAdAcList(acarousel, rowBounds,admin.getId()));
//        System.out.println(pageBean.getData().toString()+"66666666666666666666");


        String json = JSONUtil.objectToJson(pageBean);
//        System.out.println(json);
        return json;
    }

    //查到广告总数
    @RequestMapping("carouselCount")
    @ResponseBody
    public String count(Acarousel acarousel, HttpServletRequest request, HttpServletResponse response) throws IOException {


        int curPage = Integer.valueOf(request.getParameter("page"));
        int pageSize = Integer.valueOf(request.getParameter("limit"));

//        System.out.println(acarousel.toString());

        RowBounds rowBounds = new RowBounds((curPage - 1) * pageSize, pageSize);
        PageBean<Acarousel> pageBean = new PageBean<>();

        pageBean.setCode(0);
        int count = carouselService.selectAdAcListCount(acarousel);

        pageBean.setCount(count);
        pageBean.setData(carouselService.selectAdAcList(acarousel, rowBounds));

        String json = JSONUtil.objectToJson(pageBean);
        return json;
    }


    //广告列表禁用
    @RequestMapping("carouselForbidden")
    @ResponseBody
    public String acarouselForbidden(@RequestBody Acarousel acarousel, HttpServletRequest request) throws IOException {
//        System.out.println("嗯" + users.toString());
        boolean s = carouselService.acarouselForbidden(acarousel);
        if (s == true) {
            return "禁用成功";
        }
        return "禁用失败";
    }


    //广告展示
    @RequestMapping("carouselStart")
    @ResponseBody
    public String carouselStart(@RequestBody Acarousel acarousel, HttpServletRequest request) throws IOException {
//        System.err.println("要展示了启用");
//        System.out.println(aId);
        boolean s = carouselService.carouselStart(acarousel);
        if (s == true) {
            return "展示成功";
        }
        return "展示失败";
    }
    //广告通过
    @RequestMapping("carouselPass")
    @ResponseBody
    public String carouselPass(String id, HttpServletRequest request) throws IOException {
//        System.out.println("嗯" + users.toString());
        System.err.println("进来了啊"+id+"通过了");
        boolean s = carouselService.carouselPass(id);
        if (s == true) {
            return "启用成功";
        }
        return "启用失败";
    }
    //广告审核不通过
    @RequestMapping("carouselNoPass")
    @ResponseBody
    public String carouselNoPass(String aId, HttpServletRequest request) throws IOException {
//        System.out.println("嗯" + users.toString());
//        System.out.println("进来了啊");
        boolean s = carouselService.carouselNoPass(aId);
        if (s == true) {
            return "更新成功";
        }
        return "更新失败";
    }

    //广告投放跳转页面
    @RequestMapping("turnAdver")
    public String turnAdver() {
//        Admin admin = hostHolder.getAdmin();
//        if (admin.getRoleId() == 1L || admin.getRoleId() == 3L) {
//            System.out.println("店要转了");
//
//            return "carousel";
//
//        } else {
//            System.out.println("分店要转了");
            return "sAdvertisement";
//        }

    }

    //上传广告
    @RequestMapping("upLoadAdvertisement")
    @ResponseBody
    public CommonResult upLoadAdvertisement(@RequestBody MultipartFile file) {
        Acarousel acarousel = new Acarousel();

        // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.exists()){
            if (folder.isDirectory()) {
                folder.mkdirs();
            }
        }
        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;

            acarousel.setCreateTime(new Date());
            acarousel.setImageUrl(filePath);
            carouselService.addPicture(acarousel);
//            aItemImg.setIsMain(1);
//            aItemImg.setCreatedTime(new Date());
//            aItemImg.setSort(1);
//            aItemImg.setUrl(filePath);
//            aItemService.addItemImage(aItemImg);

        } catch (IOException e) {
            return CommonResult.failed("网络异常");
        }

        return CommonResult.success(acarousel);
    }


    /**
     * 商品图片的上传及关联
     */
    @ResponseBody
    @RequestMapping("/upLoadText")
    public JSONObject insertGoodURL(@RequestParam(value = "file")MultipartFile file, @RequestParam(value = "goodId")String goodID) throws IOException {
        int goodId = Integer.parseInt(goodID);
//        System.out.println(goodId);
        JSONObject res = new JSONObject();
        JSONObject resUrl = new JSONObject();
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
        String filename2 = df.format(new Date()) ;
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String path = "F:\\IEDA\\IntelliJ IDEA 2019.3.3\\gitee\\huhu-shop\\huhu-shop\\shop-admin\\src\\main\\resources\\static\\images";//http://localhost:8080/img
//        D:\IdeaProjects\doudouparking\src\main\resources\static\img\
        File filePhotoPath = new File(path);
        //判断这个路径是否存在，如果不存在创建这个路径
        if (!filePhotoPath.isDirectory()) {
            filePhotoPath.mkdir();
        }
        String filenames = filename2 + "." + ext;
        String pathname = path + filenames;
        file.transferTo(new File(pathname));//创建文件
        //数据库加路径
        String imgUrl = "img/"+filenames;
//        goodService.insertGoodURL(goodId,imgUrl);
//        resUrl.put("src", filenames);
//        res.put("msg", "");
//        res.put("code", 0);
//        res.put("data", resUrl);
        return res;
    }
    //总后台添加广告
    @RequestMapping("/findOption")
    @ResponseBody
    public String addAdvertising(@RequestBody Acarousel acarousel,HttpServletRequest request) throws IOException {
//        String type = request.getParameter("type");
//        System.err.println(acarousel.toString());
//        System.err.println(type);
            int i = carouselService.addAdvertising(acarousel);
            if (i>=1){
                return "上传成功";
            }else {
                return "上传失败";
            }
//        return "成功";


    }
    //获取广告列表下拉框的值
    @RequestMapping("/getChoose")
    @ResponseBody
    public List<ChooseSelectVo> getChoose(@RequestParam("choose") String choose){

        if(choose.equals("1")){
            return carouselService.getCa();
        }else if (choose.equals("2")){
            return carouselService.getIt();
        }



        return null;
    }


}

